package com.example.video.common.config;



import com.example.video.common.http.HttpResult;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;


/**
 * 捕获并处理全局异常
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 捕获并处理所有自定义异常
     */
    @ResponseBody
    @ExceptionHandler(value = BusinessException.class)
    public HttpResult handle(BusinessException e) {
        if (e.getErrorCode() != null) {
            return HttpResult.fail(e.getErrorCode());
        }
        return HttpResult.fail(e.getMessage());
    }

    /**
     * 捕获并处理方法参数未验证异常
     */
    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public HttpResult handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String message = null;
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                message = fieldError.getField()+fieldError.getDefaultMessage();
            }
        }
        return HttpResult.validateFailed(message);
    }

    /**
     * 捕获并处理绑定异常
     */
    @ResponseBody
    @ExceptionHandler(value = BindException.class)
    public HttpResult handleValidException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        String message = null;
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                message = fieldError.getField()+fieldError.getDefaultMessage();
            }
        }
        return HttpResult.validateFailed(message);
    }

    /**
     * 上传文件过大的异常
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = MaxUploadSizeExceededException.class)
    public HttpResult handleFileSizeException(MaxUploadSizeExceededException e){
        return HttpResult.fail(e.getMessage());
    }
}